from django.shortcuts import render

"""
 1. 获取code
 2. 通过code获取access_token
 3. 通过access_token获取openid
"""
# Create your views here.
from django.views import View
from django.http import HttpResponse, JsonResponse
from QQLoginTool.QQtool import OAuthQQ


class QQUserView(View):
    def get(self, request):
        # 1. 获取code
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '没有code参数'})

        # client_id=None,  在创建应用的时候的id
        # client_secret=None,  在创建应用的时候的密钥
        # redirect_uri=None,  用户扫描同意之后，跳转的url
        # 我们申请的 客户端id
        QQ_CLIENT_ID = '101474184'
        # 我们申请的 客户端秘钥
        QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
        # 我们申请时添加的: 登录成功后回调的路径
        QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state='panghu')

        # 2. 通过code获取token
        access_token = qq.get_access_token(code)
        # 3. 通过token获取openid
        # '9AE1A40F6CEC9A03AB7BB3276BF7104B'
        openid = qq.get_open_id(access_token)

        # 4. 根据openid进行数据的查询
        from apps.oauth.models import OAuthQQUser
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 如果查询不出说明之前没有绑定过，要把 openid以响应的方式发送给前端
            from apps.oauth.common import generic_open_id
            secret_openid = generic_open_id(openid)
            return JsonResponse({'code': 1, 'access_token': secret_openid})
        else:
            # 如果查询出 用户信息, 说明用户之前绑定过，设置状态保持，跳转到制定的页面
            from django.contrib.auth import login
            # 第二个参数user必须是User的实例对象
            login(request, qquser.user)

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', qquser.user.username, max_age=14 * 24 * 3600)

            return response

    def post(self, request):
        import json
        data = json.loads(request.body.decode())
        print(data)
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        secret_data = data.get('access_token')  # acccess_token 实质还是openid

        from apps.oauth.common import check_open_id
        openid = check_open_id(secret_data)

        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        import re
        if not re.match('1[3-9]\d{8}', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                      'errmsg': '请输入8-20位的密码'})

        from django_redis import get_redis_connection
        # 链接数据库获取短信验证码
        redis_cli = get_redis_connection('code')
        redis_sms_code = redis_cli.get(mobile)

        redis_cli.delete(mobile)

        if redis_sms_code is None:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'})

        if redis_sms_code.decode() != sms_code:
            return JsonResponse({'code': 400, 'errmsg': '验证码错误'})

        # 4. 根据手机号判断用户信息
        from apps.users.models import User
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果查询不到，则新建用户
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password,
            )
        else:
            # 判断密码是否正确
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '手机号或密码错误'})

        # 5.绑定用户信息(信息入库)
        from apps.oauth.models import OAuthQQUser
        OAuthQQUser.objects.create(openid=openid, user=user)

        # 6. 状态保持
        from django.contrib.auth import login
        login(request,user)

        # 7. 设置cookie
        response = JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',user.username,max_age=14*24*3600)

        return response
